﻿using StarryEdge.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
using System.Threading.Tasks;

namespace StarryEdge.Plugin
{
    public class PluginsAssemblyLoadContext : AssemblyLoadContext
    {
        private AssemblyDependencyResolver _resolver;
        private IStarryEdgeLog _starryEdgeLog;
        public PluginsAssemblyLoadContext(string path, IStarryEdgeLog starryEdgeLog) : base(true)
        {
            _resolver = new AssemblyDependencyResolver(path);
            _starryEdgeLog = starryEdgeLog;
        }

        protected override Assembly? Load(AssemblyName assemblyName)
        {
            string assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName);
            if (assemblyPath != null)
            {
                _starryEdgeLog.LogRun($"Loading Assembly {assemblyPath}");
                //return LoadFromAssemblyPath(assemblyPath);
                return LoadFromStream(File.OpenRead(assemblyPath));
            }
            return null;
        }
    }
}
